package com.jemmyee.shop.web.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * 全局配置文件，主要进行dom操作
 * @author jemmyee
 * @date 2010-6-9
 */
public class ConfigXmlUtils{
	//测试路径
	private static String filePath="d:/config.xml";
	
	public static void main(String[] args) throws MalformedURLException, DocumentException {
    
	}
	

    /**
    * @Description:读取xml，返回Document
    * @author:jemmyee@gmail.com
    * @date:2010-11-24
    */
    public static Document read(String fileName){
        SAXReader reader = new SAXReader();
        Document document=null;
		try {
			document = reader.read(new File(fileName));
		} catch (DocumentException e) {
			e.printStackTrace();
		}
        return document;
     }    
    

    /**
    * @Description: 得到root节点
    * @author:jemmyee@gmail.com
    * @date:2010-11-24
    */
    public static Element getRootElement(Document doc){
        return doc.getRootElement();
    }
	
 
    /**
    * @Description:得到配置
    * @author:jemmyee@gmail.com
    * @date:2010-11-24
    */
    public static String getConfig(String fileName,String ckey){
    	Document document=read(fileName);
    	String configs="";
    	List list = document.selectNodes("/configs/config" );
    	Iterator it= list.iterator();
    	while(it.hasNext()){
    		Element item =(Element)it.next();
    		Element key=item.element("ckey");
    		Element val=item.element("cval");
    		if(key.getTextTrim().equals(ckey)){
    			configs=val.getTextTrim();
    		}
    	}
    	return configs;
    }
    

    /**
    * @Description:修改
    * @author:jemmyee@gmail.com
    * @date:2010-11-24
    */
    public static void edit(String fileName,String ckey,String cval){
    	Document document=read(fileName);
        List list = document.selectNodes("/configs/config" );
        Iterator it= list.iterator();
        while(it.hasNext()){
           Element item =(Element)it.next();
           Element key=item.element("ckey");
           Element val=item.element("cval");
           if(key.getTextTrim().equals(ckey)){
        	   val.setText(cval);
        	   XMLWriter writer;
       		try {
       			writer = new XMLWriter(new FileOutputStream(new File(fileName)));
       			writer.write(document);
       		    writer.close();
       		} catch (IOException e) {
       			e.printStackTrace();
       		}
           }
           
        }
    }
	
}
